const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
const glob = require('glob');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ImageminPlugin = require('imagemin-webpack-plugin').default
//消除冗余的css
const PurifyCssWebpack = require('purifycss-webpack');
// html模板
const HtmlWebpackPlugin = require('html-webpack-plugin');
//静态资源输出
const CopyWebpackPlugin = require('copy-webpack-plugin');

// 获取html-webpack-plugin参数的方法
var getHtmlConfig = function (name, chunks) {
  console.log('\x1b[33m%s\x1b[0m', process.env.BASE_URL);  
  return {
    template: `./src/pages/${name}/${name}.html`,
    filename: `${name}.html`,
    // favicon: './favicon.ico',
    // title: title,
    inject: true,
    hash: true, //开启hash  ?[hash]
    chunks: chunks,
    minify: process.env.NODE_ENV === 'development' ? false : {
      removeComments: true, //移除HTML中的注释
      collapseWhitespace: true, //折叠空白区域 也就是压缩代码
      removeAttributeQuotes: true, //去除属性引用
    },
  };
};



// 获取 entry 参数的方法
function getEntry() {
  var entry = {};
  //读取src目录所有page入口
  glob.sync('./src/pages/**/*.ts')
    .forEach(function (name) {
      var start = name.indexOf('src/') + 4,
        end = name.length - 3;
      var eArr = [];
      var n = name.slice(start, end);
      n = n.slice(0, n.lastIndexOf('/')); //保存各个组件的入口 
      n = n.split('/')[1];
      eArr.push(name);
      entry[n] = eArr;
    });
  return entry;
};


module.exports = {
  // 入口文件
  entry: getEntry(),
  module: {
    rules: [{ // html 热更新
        test: /\.(htm|html)$/,
        use: [
          'raw-loader'
        ]
      },
      { // css loader
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      },
      { // less loader
        test: /\.less$/,
        // 区别开发环境和生成环境
        use: process.env.NODE_ENV === 'development' ? ['style-loader', 'css-loader', 'less-loader'] : ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'less-loader'],
          // css中的基础路径
          publicPath: './'
        })
      },
      {
        test: /\.(gif|png|jpe?g|svg)$/i,
        use: [
          'file-loader',
        ]
      },
    ]
  },
  plugins: [
    //静态资源输出
    new CopyWebpackPlugin([{
      from: path.resolve(__dirname, 'src/assets'),
      to: './assets',
      ignore: ['.*']
    }]),
    // 消除冗余的css代码
    new PurifyCssWebpack({
      paths: glob.sync(path.join(__dirname, '../src/pages/*/*.html'))
    }),
    new webpack.HashedModuleIdsPlugin(), // vendor hash 变化修复
     // 图片压缩
     new ImageminPlugin({
      test: /\.(jpe?g|png|gif|svg)$/i,
      disable: process.env.NODE_ENV === 'development', // Disable during development
      pngquant: {
        quality: '95-100' // 图片品质
      }
    })
  ],
  // 提取公共代码
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: { // 抽离第三方插件
          test: /node_modules/, // 指定是node_modules下的第三方包
          chunks: 'initial',
          name: 'vendor', // 打包后的文件名，任意命名    
          // 设置优先级，防止和自定义的公共代码提取时被覆盖，不进行打包
          priority: 10
        }
      }
    }
  },
}
//配置页面
const entryObj = getEntry();
const htmlArray = [];
Object.keys(entryObj).forEach(element => {
  htmlArray.push({
    _html: element,
    title: '',
    chunks: ['vendor', element]
  })
})

//自动生成html模板
htmlArray.forEach((element) => {
  module.exports.plugins.push(new HtmlWebpackPlugin(getHtmlConfig(element._html, element.chunks)));
})